package com.ayuku.retail.ui.kasir;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.ayuku.commons.AyBigDecimal;
import com.ayuku.commons.AyukuDB;
import com.ayuku.commons.Util;
import com.ayuku.retail.persistence.model.ItemSales;
import com.ayuku.retail.persistence.model.Sales;
import com.ayuku.retail.persistence.model.TrxTempSale;

public class FormBayar extends org.eclipse.swt.widgets.Dialog {

	private Shell dialogShell;
	private Label label1;
	private Label label9;
	private AyBigDecimal txtGrandTotal;
	private Label label8;
	private AyBigDecimal txtDiscount;
	private AyBigDecimal txtDiscountPercent;
	private Label label7;
	private AyBigDecimal txtKembali;
	private Label label2;
	private AyBigDecimal txtBayar;
	private SalesCash frmSalescash;
	private double subTotal = 0.0;
	private Label label;
	private Label label_1;
	private String trxCode;
	private Button btnOk;
	private Label lblNewLabel;

	public String getTrxCode() {
		return trxCode;
	}

	public void setTrxCode(String trxCode) {
		this.trxCode = trxCode;
	}

	public SalesCash getFrmSalescash() {
		return frmSalescash;
	}

	public void setFrmSalescash(SalesCash frmSalescash) {
		this.frmSalescash = frmSalescash;
	}

	public double getSubTotal() {
		return subTotal;
	}

	public void setSubTotal(double subTotal) {
		this.subTotal = subTotal;
	}

	public FormBayar(Shell parent, int style) {
		super(parent, style);
	}

	public void open() {

		try {

			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM
					| SWT.APPLICATION_MODAL);
			dialogShell.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
		
			dialogShell.setSize(449, 298);
			GridLayout gl_dialogShell = new GridLayout(4, false);
			gl_dialogShell.verticalSpacing = 8;
			dialogShell.setLayout(gl_dialogShell);

			dialogShell.layout();

			label_1 = new Label(dialogShell, SWT.SEPARATOR | SWT.HORIZONTAL);
			label_1.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			GridData gd_label_1 = new GridData(SWT.FILL, SWT.CENTER, false,
					false, 4, 1);
			gd_label_1.heightHint = 10;
			label_1.setLayoutData(gd_label_1);

			label7 = new Label(dialogShell, SWT.NONE);
			label7.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			label7.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true,
					false, 1, 1));
			label7.setText("Discount");
			label7.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 16, SWT.NORMAL));

			txtDiscountPercent = new AyBigDecimal(dialogShell, SWT.BORDER);
			GridData gd_txtDiscountPercent = new GridData(SWT.FILL, SWT.CENTER,
					false, false, 1, 1);
			gd_txtDiscountPercent.widthHint = 79;
			txtDiscountPercent.setLayoutData(gd_txtDiscountPercent);
			txtDiscountPercent.setFont(org.eclipse.wb.swt.SWTResourceManager
					.getFont("Segoe UI", 18, SWT.NORMAL));
			txtDiscountPercent.setStringFormatter("#0.##");

			txtDiscountPercent.getOrgComponent().getControl()
					.addFocusListener(new FocusAdapter() {
						public void focusGained(FocusEvent evt) {
							txtDiscountPercent.getOrgComponent().getControl()
									.selectAll();
						}
					});

			txtDiscountPercent.getOrgComponent().getControl()
					.addKeyListener(new KeyAdapter() {
						public void keyReleased(KeyEvent evt) {

							txtDiscountPercentPressed(evt);
						}
					});

			label9 = new Label(dialogShell, SWT.NONE);
			label9.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			label9.setText("%  ");
			label9.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 16, SWT.NORMAL));

			txtDiscount = new AyBigDecimal(dialogShell, SWT.BORDER);
			GridData gd_txtDiscount = new GridData(SWT.FILL, SWT.CENTER, false,
					false, 1, 1);
			gd_txtDiscount.widthHint = 161;
			txtDiscount.setLayoutData(gd_txtDiscount);
			txtDiscount.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 18, SWT.NORMAL));
			txtDiscount.setStringFormatter("###,###,##0.##");
			txtDiscount.getOrgComponent().getControl()
					.addKeyListener(new KeyAdapter() {
						public void keyReleased(KeyEvent evt) {

							changeDiscountPercent();
						}
					});
			txtDiscount.setValue(frmSalescash.txtDiscAmount.getValue());

			label8 = new Label(dialogShell, SWT.NONE);
			label8.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			label8.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true,
					false, 1, 1));
			label8.setText("Grand Totala:");
			label8.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 16, SWT.NORMAL));

			txtGrandTotal = new AyBigDecimal(dialogShell, SWT.BORDER);
			txtGrandTotal.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(175, 238, 238));
			txtGrandTotal.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
					false, false, 3, 1));
			txtGrandTotal.setFont(org.eclipse.wb.swt.SWTResourceManager
					.getFont("Segoe UI", 18, SWT.NORMAL));

			txtGrandTotal.setValue(frmSalescash.txtGrandTotal.getValue());
			txtGrandTotal.getOrgComponent().getControl()
					.addFocusListener(new FocusAdapter() {
						@Override
						public void focusGained(FocusEvent arg0) {
							txtBayar.setFocus();
						}
					});
			label1 = new Label(dialogShell, SWT.NONE);
			label1.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			label1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true,
					false, 1, 1));
			label1.setText("CASH:");
			label1.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 16, SWT.NORMAL));

			txtBayar = new AyBigDecimal(dialogShell, SWT.BORDER);
			txtBayar.getOrgComponent().getControl()
					.addFocusListener(new FocusAdapter() {
						@Override
						public void focusGained(FocusEvent arg0) {
							txtBayar.setFocus();
						}
					});
			txtBayar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
					false, 3, 1));
			txtBayar.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 18, SWT.NORMAL));

			txtBayar.getOrgComponent().getControl()
					.addKeyListener(new KeyAdapter() {
						public void keyReleased(KeyEvent evt) {
							txtBayarKeyPressed(evt);
						}
					});

			label2 = new Label(dialogShell, SWT.NONE);
			label2.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(100, 149, 237));
			label2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true,
					false, 1, 1));
			label2.setText("CHANGE");
			label2.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 16, SWT.NORMAL));

			txtKembali = new AyBigDecimal(dialogShell, SWT.BORDER);
			txtKembali.getOrgComponent().getControl()
					.addFocusListener(new FocusAdapter() {
						@Override
						public void focusGained(FocusEvent arg0) {
							btnOk.setFocus();
						}
					});
			txtKembali.setBackground(org.eclipse.wb.swt.SWTResourceManager
					.getColor(173, 216, 230));
			txtKembali.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
					false, 3, 1));
			txtKembali.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 18, SWT.NORMAL));

			label = new Label(dialogShell, SWT.SEPARATOR | SWT.HORIZONTAL);
			label.setBackground(org.eclipse.wb.swt.SWTResourceManager.getColor(
					100, 149, 237));
			GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, true, false,
					4, 1);
			gd_label.heightHint = 10;
			label.setLayoutData(gd_label);

			txtDiscountPercent.setValue(frmSalescash.txtDiscountPercent
					.getValue());
			
			lblNewLabel = new Label(dialogShell, SWT.NONE);
			lblNewLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL));
			lblNewLabel.setBackground(org.eclipse.wb.swt.SWTResourceManager.getColor(100, 149, 237));
			lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 3, 1));
			lblNewLabel.setText("ESC = Cancel, Tab = pindah input");

			btnOk = new Button(dialogShell, SWT.NONE);
			btnOk.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.keyCode == SWT.ARROW_DOWN) {
						txtDiscount.setFocus();
					} else if (arg0.keyCode == SWT.ARROW_UP) {
						txtBayar.setFocus();
					}
				}
			});
			btnOk.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent arg0) {
					doProsesBayar(arg0);
				}
			});
			btnOk.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
					"Segoe UI", 12, SWT.NORMAL));
			GridData gd_btnOk = new GridData(SWT.RIGHT, SWT.CENTER, false,
					false, 1, 1);
			gd_btnOk.widthHint = 92;
			btnOk.setLayoutData(gd_btnOk);
			btnOk.setText("&OK");
			btnOk.setBackground(org.eclipse.wb.swt.SWTResourceManager.getColor(
					100, 149, 237));

			dialogShell.open();
			Util.setCenter(dialogShell);
			txtBayar.setFocus();
			
			Display display = dialogShell.getDisplay();
			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** proses Pembarayan
	 * 
	 * @param arg0
	 */
	protected void doProsesBayar(SelectionEvent arg0) {

			int style = SWT.APPLICATION_MODAL | SWT.NO | SWT.YES;
			MessageBox messageBox = new MessageBox(dialogShell, style);
			messageBox.setText("Information");
			messageBox.setMessage("Cetak Struk Penjualan?");


			try {
				AyukuDB.getPersist().setAutoCommit(false);

				Sales sales = new Sales();
				sales.setTrxCode(frmSalescash.getTxtTrxNo().getValue());
				sales.setTrxDate(frmSalescash.getTrxDateCal().getTime());
				sales.setCreatedDate(Calendar.getInstance().getTime());
				sales.setDiscount(BigDecimal.valueOf(0.0));
				sales.setCustCode("Direct");
				sales.setIsCash(1);
				sales.setChange(txtKembali.getValue());
				sales.setCharge(txtBayar.getValue());
				sales.setTax(BigDecimal.valueOf(0.0));
				sales.setTermint(0);
				sales.setCreatedBy(Util.getCurrentUser().getUname());
				sales.setModifiedBy(Util.getCurrentUser().getUname());
				sales.setModifiedDate(Calendar.getInstance().getTime());
				sales.setGrandTotal(BigDecimal.valueOf(subTotal));
				sales.setPiutang(BigDecimal.valueOf(0.0));
				sales.setOperator(Util.getCurrentUser().getUname());
				sales.setSubTotal(BigDecimal.valueOf(subTotal));
				// Simpan ke database

				AyukuDB.getPersist().insert(sales);
				
				
				List<TrxTempSale> lst = AyukuDB.getPersist().readList(
						TrxTempSale.class,
						"SELECT * FROM TRX_TEMP_SALE order by idx");

			
				for (int i = 0; i < lst.size(); i++) {
					TrxTempSale sl = lst.get(i);
					ItemSales itemSales = new ItemSales();
					itemSales.setTrxCode(frmSalescash.getTxtTrxNo().getValue());
					itemSales.setItemName(sl.getKeterangan());
					itemSales.setItemCode(sl.getBarcode());
					itemSales.setOriPrice(sl.getPrice());
					itemSales.setQty(sl.getQty());
					itemSales.setDiscount(sl.getDisc());
					itemSales.setSubTotal(sl.getTotal());
					//itmPurc.setIdx(sl.getIdx().longValue());
					itemSales.setCreatedDate(Calendar.getInstance().getTime());
					itemSales.setCreatedBy(Util.getCurrentUser().getUname());
					itemSales.setModifiedBy(Util.getCurrentUser().getUname());
					itemSales.setModifiedDate(Calendar.getInstance().getTime());
					AyukuDB.getPersist().insert(itemSales);
					System.out.println("*** Detail no: " + i);
				}
				
				AyukuDB.getPersist().commit();
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					AyukuDB.getPersist().rollback();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} finally {
				try {
					AyukuDB.getPersist().setAutoCommit(true);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			System.out.println("Simpan Ke database ....");

			if (messageBox.open() == SWT.YES) {
				// CETAK
			}
			dialogShell.dispose();
	
	}

	protected void txtDiscountPercentPressed(KeyEvent evt) {

		if (evt.keyCode == 0) {

		}

		changeDiscount();

		frmSalescash.txtDiscountPercent.setValue(txtDiscountPercent.getValue());

		frmSalescash.txtDiscAmount.setValue(txtDiscount.getValue());

	}

	protected void changePPn() {
		txtDiscount.getValue().doubleValue();
		changeGrandTotal();
	}

	protected void changeKembalian() {
		double bayar = txtBayar.getValue().doubleValue();
		txtKembali.setValue(BigDecimal.valueOf(bayar
				- txtGrandTotal.getValue().doubleValue()));
	}

	protected void changeGrandTotal() {
		double grandTotal = subTotal - txtDiscount.getValue().doubleValue();

		txtGrandTotal.setValue(BigDecimal.valueOf(grandTotal));
		frmSalescash.txtGrandTotal.setValue(BigDecimal.valueOf(grandTotal));
		frmSalescash.txtDisplayTotal.setText("TOTAL: "
				+ Util.formatToNumber(grandTotal));

	}

	protected void changeDiscountPercent() {
		double percent = txtDiscount.getValue().doubleValue() / subTotal * 100;
		txtDiscountPercent.setValue(BigDecimal.valueOf(percent));
		changeGrandTotal();

		frmSalescash.txtDiscountPercent.setValue(txtDiscountPercent.getValue());

		frmSalescash.txtDiscAmount.setValue(txtDiscount.getValue());

	}

	protected void changeDiscount() {
		double discount = txtDiscountPercent.getValue().doubleValue()
				* subTotal / 100;
		txtDiscount.setValue(BigDecimal.valueOf(discount));
		changeGrandTotal();
	}

	private void txtBayarKeyPressed(KeyEvent evt) {

		if (evt.keyCode == SWT.CR) {
			btnOk.setFocus();
		} else if (evt.keyCode == SWT.ARROW_UP) {
			txtDiscountPercent.setFocus();
		} else {
			changeKembalian();
		}

	}

}
